<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\GoodsPicPrimaryModel;
use App\Models\GoodsPicAllModel;
use App\Models\OrderGoodsModel;
use App\Models\SupplyModel;
use App\Models\UserModel;
use App\Utils\ControllerModelTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SupplyController extends ApiController
{
    use ControllerModelTrait;
    const CACHE_KEY = 'supply-';

    /**
     * 商家列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getList(Request $request): JsonResponse
    {
        $Model = SupplyModel::getModel($request)
            ->select('ID', 'CName', 'Manager', 'Mobile', 'QQ', 'Addr', 'Weixin', 'ITime', 'building', 'floor', 'floor_text', 'room', 'shipping_type');
        $paginate = $this->getPagedData($Model, $request, 'ID');
        // 推荐商品
        if ($request->input('recommend')) {
            $data = $this->getSupplyListWithGoods($paginate, $request);
            return $this->success($this->getPaginate($paginate, $data));
        } else
            return $this->successPaginate($paginate);
    }

    /**
     * 获取带推荐商品的商家信息
     * @param $paginate
     * @param $request
     * @return mixed
     */
    protected function getSupplyListWithGoods($paginate, $request): mixed
    {
        $items = $paginate->items();
        $data = json_decode(json_encode($items), true);
        $supplyIds = array_column($data, 'ID');
        $userCollection = UserModel::whereIn('sid', $supplyIds)->select('id', 'sid', 'username')->get();
        foreach ($data as &$value) {
            if ($request->input('authed')) {
                if ($user = $userCollection->where('sid', $value['ID'])->first())
                    $value['user'] = $user;
            }
            $value['goods'] = $this->getSupplyRecommendGoods($value['ID']);
            $value['totalGoods'] = GoodsPicPrimaryModel::where('SID', $value['ID'])->count('ID');
            $value['saleCount'] = OrderGoodsModel::where('sid', $value['ID'])->where('done_status', 1)->sum('goods_num');
        }
        return $data;
    }

    /**
     * 获取商家详情
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getInfo(Request $request): JsonResponse
    {
        $sid = $this->verifyId('sid');
        $supply = SupplyModel::where('ID', $sid)->first();
        if ($supply) {
            $supply->totalGoods = GoodsPicPrimaryModel::where('SID', $sid)->count('ID') ;
            $supply->updateNewTime = GoodsPicPrimaryModel::where('SID', $sid)->orderByDesc('ITime')->value('ITime');
            $supply->goods = $this->getSupplyRecommendGoods($sid);
        }
        return $this->success($supply);
    }

    /**
     * 商家信息变更
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doSave(Request $request): JsonResponse
    {
        $id = $this->verifyId('ID');
        $supply = SupplyModel::where('ID', $id)->first();
        if ($supply) {
            $data = $request->only(['building', 'floor', 'room', 'floor_text', 'shipping_type']);
            SupplyModel::where('ID', $id)->update(array_filter($data));
            self::setSupplyCache($id);
        }
        return $this->success();
    }

    /**
     * 商家下架
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function setStatus(Request $request): JsonResponse
    {
        $id = $request->input('ID', 0);
        if ($id > 0) {
            SupplyModel::where('ID', $id)->update(['status' => $request->input('status', 0)]);
            GoodsPicPrimaryModel::where('SID', $id)->update(['PStatus' => $request->input('status', 0) ? 0 : 3]);
            GoodsPicAllModel::where('SID', $id)->where('PID', 0)->update(['PStatus' => 3]);
        }
        return $this->success();
    }

    /**
     * 获取全部商家
     * @return JsonResponse
     */
    public function getAllSupply(): JsonResponse
    {
        $collection = self::getAllSupplyCache();
        return $this->success($collection);
    }

    /**
     * 获取相同手机号的商家
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getSameMobileSupply(): JsonResponse
    {
        $mobile = $this->verifyString('mobile');
        $collection = self::getAllSupplyCache()->where('Mobile', $mobile);
        return $this->success(array_values($collection->toArray()));
    }

    /**
     * 商家推荐商品列表
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getGoodsList(Request  $request): JsonResponse
    {
        $sid = $this->verifyId('sid');
        return $this->success($this->getSupplyRecommendGoods($sid));
    }

    /**
     * 获取商家推荐商品
     * @param $sid
     * @return mixed
     */
    private function getSupplyRecommendGoods($sid): mixed
    {
        $cacheKey = 'supplyRecommendGoods-'.$sid;
        if (!Cache::has($cacheKey)) {
            $goods = GoodsPicPrimaryModel::where('SID', $sid)->where('PStatus', 0)
                ->select(['ID', 'PName', 'Path', 'FName', 'IsEncry', 'PHotNum'])->orderByDesc('ID')->limit(9)->get();
            if ($goods)
                Cache::put($cacheKey, $goods, 12 * 3600);
        }
        return Cache::get($cacheKey);
    }

    /**
     * 创建商家信息缓存
     * @param $id
     * @return void
     */
    public static function setSupplyCache($id): void
    {
        $supply = SupplyModel::where('ID', $id)
            ->select(['ID', 'CName', 'Cweb', 'Mobile', 'QQ', 'Weixin', 'Addr', 'Addr1', 'Licence_img', 'building', 'floor', 'room', 'shipping_type', 'ITime'])->first();
        $supply->updateNewTime = GoodsPicPrimaryModel::where('SID', $id)->orderByDesc('ITime')->value('ITime');
        $supply->totalGoods = GoodsPicPrimaryModel::where('SID', $id)->count('ID') ;
        Cache::put(self::CACHE_KEY . $id, $supply, 60);
    }

    /**
     * 获取商家信息缓存
     * @param $id
     * @return mixed
     */
    public static function getSupplyCache($id): mixed
    {
        if (!Cache::has(self::CACHE_KEY . $id))
            self::setSupplyCache($id);
        return Cache::get(self::CACHE_KEY . $id);
    }

    /**
     * 获取全部商家缓存
     * @return mixed
     */
    public static function getAllSupplyCache(): mixed
    {
        if (!Cache::has('all_supply'))
            Cache::put('all_supply', SupplyModel::where('status', 1)->select(['ID', 'CName', 'Mobile'])->get(), 180);
        return Cache::get('all_supply');
    }
}
